let table;
let form;
let $;

layui.config({
    base: 'static/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['layer', 'form', 'element'], function () {
    form = layui.form;
    table = layui.table;
    element = layui.element;
    $ = layui.$;
});

window.onmessage = (event) => {
    if (event.source === window && event.data === 'main-world-port') {
        let port = event.ports[0];

        port.onmessage = (event) => {
            if (event.data.message) {
                layer.msg(event.data.message);
            }

            if (event.data.cmd == 'initConfigs') {
                if (event.data.configs) {
                    let formValues = {};

                    for (let i = 0; i < event.data.configs.length; i++) {
                        let config = event.data.configs[i];
                        formValues[config.name] = config.value;
                    }

                    form.val('config-edit', formValues);
                }
            }
        }

        document.querySelector('#btnAdd').addEventListener('click', function () {
            let rows = table.getData('accountListTable');

            if (rows.length < 1) {
                // showEditDialog(null, port);
            } else {
                layer.msg('仅能配置一个账号，请先删除其他账号再操作');
            }
        });

        document.querySelector('#btnTradeSwitch').addEventListener('click', function () {
            let btn = document.querySelector('#btnTradeSwitch');

            if (btn.innerText == '启动自动评论') {
                btn.innerText = '退出自动评论';
                port.postMessage({ cmd: 'startTask' });
            } else {
                btn.innerText = '启动自动评论';
                port.postMessage({ cmd: 'stopTask' });
            }
        });

        document.querySelector('#btnSave').addEventListener('click', function () {
            var formValue = form.val('config-edit');
            let configs = [];

            for (let key in formValue) {
                configs.push({ key: key, value: formValue[key] });
            }

            if (configs.length > 0) {
                port.postMessage({ cmd: 'saveConfig', configs: configs });
            }
        });

        document.querySelector('#btnLogin').addEventListener('click', function () {
            port.postMessage({ cmd: 'accountLogin' });
        });
    }
}